package org.jmetrix.monitor.impl;

import org.jmetrix.expose.Exposer;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Konstantin Kuzmin
 * @version $Revision$
 * @since 06.10.11
 */
public class ExposerMonitor extends MonitorImpl {
    private Exposer exposer;
    private ScheduledExecutorService scheduledExecutorService;
    private long initialDelayMillis = 0;
    private long periodMillis = 1000;
    private boolean started = false;
    private long shutdownTimeoutMillis = 10000;

    public ExposerMonitor() {
    }

    @Override
    public synchronized void start() {
        if (started) {
            return;
        }
        super.start();
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    exposer.expose(getMetrixAggregator());
                } catch (Exception e) {
                    logError(e);
                }
            }
        }, initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS);
        started = true;
    }

    private void logError(final Exception e) {
        System.out.println(e); //TODO add logging
    }

    public void setExposer(final Exposer exposer) {
        this.exposer = exposer;
    }

    protected Exposer getExposer() {
        return exposer;
    }

    public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
        this.scheduledExecutorService = scheduledExecutorService;
    }

    public void setInitialDelayMillis(final long initialDelayMillis) {
        this.initialDelayMillis = initialDelayMillis;
    }

    public void setPeriodMillis(final long periodMillis) {
        this.periodMillis = periodMillis;
    }

    public synchronized void stop() {
        if (!started) {
            return;
        }
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
            try {
                scheduledExecutorService.awaitTermination(shutdownTimeoutMillis, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        super.stop();
        started = false;
    }

}
